import {defineStore} from "pinia";
import {getGroupList} from "../apis/chat/group.js";
import { userInfoStore } from "./user.js";
import {MessageFactory} from "../socket/SocketMessage.js";

const BASE_URL = 'ws://8.137.61.26:8080/chat/ws/'
const groupSocketUrl = BASE_URL + 'group/';
export const useSocketStore = defineStore('socketStore', {
    state: () => {
        return {
            socket: null,
            groupSockets: [],
            messages: [],
            isConnected: false,
            unread: 0,
            reconnectInterval: 10000,
            maxReconnectAttempts: 5,
        }
    },
    getters: {

    },
    actions: {
        async initialize(userId) {

            this.closeSockets();

            this.socket = new WebSocket(BASE_URL + userId);

            this.socket.onopen = () => {
                console.log('WebSocket connected');
            };

            this.socket.onmessage = (event) => {

                const message = JSON.parse(event.data)

                console.log('Received message:', message);

                if (message.type === 'UNREAD') {
                    this.unread = message.count
                } else if (message.type === 'text') {
                    const data = MessageFactory.parseMessage(event.data)
                    this.onMessage(data)
                } else if (message.type === 'file') {
                    const data = MessageFactory.parseMessage(event.data);
                    this.onMessage(data)
                }

            };
            this.socket.onclose = (event) => {
                console.log('WebSocket closed:', event);
                this.reconnect(userId);
            };

        },
        async initializeGroupSocket(userId) {
            const groups = await getGroupList({groupOwner: userId});
            groups.data.forEach((group) => {
              this.connectGroupSocket(group.id)
            });
        },
        async connectGroupSocket(id) {
            const socket = new WebSocket(groupSocketUrl + id);

            socket.onopen = () => {
                console.log('Group Socket open');
            }
            socket.onmessage = (event) => {
                console.log('Group Socket message', event)
                const message = JSON.parse(event.data)

                if (message.type === 'text') {
                    const data = MessageFactory.parseMessage(event.data)
                    this.onMessageGroups(message.groupId, data)
                } else if (message.type === 'file') {
                    const data = MessageFactory.parseMessage(event.data);
                    this.onMessageGroups(message.groupId, data)
                }
            };
            socket.onclose = (event) => {
                console.log('Group Socket closed:', event);
                this.reconnectGroups(id);
            };
            this.$patch((state) => {
                state.groupSockets[id] = socket;
            })
        },
        // 关闭所有socket
        closeSockets() {
            if (this.socket && this.socket.readyState === WebSocket.OPEN)
                this.socket.close();
            this.groupSockets.forEach((socket) => {
                if (socket.readyState === WebSocket.OPEN)
                    socket.close();
            });
            this.groupSockets = [];
        },
        sendMessage(message) {
            if (this.socket && this.socket.readyState === WebSocket.OPEN)
                this.socket.send(JSON.stringify(message));
            else
                console.error('WebSocket is not open. Ready state:', this.socket.readyState);
        },
        sendMessageGroups(sessionId, message) {
            console.log('Sending message:', message);
            const socket = this.groupSockets[sessionId]
            if (socket && socket.readyState === WebSocket.OPEN)
                socket.send(JSON.stringify(message));
            else
                console.error('WebSocket is not open. Ready state:', socket.readyState);
        },
        async clearUnread(groupId, userId) {
          this.sendMessage({
              type: 'CLEAR_UNREAD',
              conversationId: groupId,
              sender: userId
          })
        },
        onMessage(message) {
            this.messages.push(message)
        },
        onMessageGroups(groupId, message) {
            if (message.sender === userInfoStore().id)
                return;
            this.messages.push(message);
        },
        async reconnect(userId) {
            setTimeout(() => {
                console.log('Reconnecting...')
                this.initialize(userId)
            }, 5000)
        },
        async reconnectGroups(groupId) {
            setTimeout(() => {
                console.log('Group Socket Reconnecting...')
                this.connectGroupSocket(groupId)
            }, 5000)
        }
    }
})
